<?php

namespace App\Http\Controllers\Admin;

use App\Enums\ResponseEnum;
use App\Http\Controllers\AdminController;
use App\Library\ClientIp;
use App\Models\Logs\LoginLog;
use Illuminate\Http\Request;
use YangJiSen\CacheUserProvider\CacheForget;

class AuthController extends AdminController
{
    public function login(Request $request)
    {
        $request->validate([
            'username' => 'required',
            'password' => 'required',
        ]);
        $credentials = $request->only(['username', 'password']);
        $token = $this->guard()->attempt([
            'username' => base64_decode($credentials['username']),
            'password' => base64_decode($credentials['password']),
            'status' => 1,
        ]);
        if (!empty($token)) {
            $data = [];
            $user = $this->guard()->user();
            $ip = getClientIp();
            if ($user) {
                $data['userInfo'] = base64_encode(json_encode([
                    "avatar" => $user['avatar'],
                    "userName" => $user['username'],
                    "displayName" => $user['display_name'],
                    "ip" => $ip,
                    "ipAddress" => ClientIp::getLocation($ip)["region"],
                    'loginTime' => date('Y-m-d H:i:s'),
                ]));
            }
            LoginLog::createLoginLog('认证成功', $user['id']);
            return $this->respondWithToken($token, $data);
        }
        return $this->error(ResponseEnum::USER_SERVICE_LOGIN_ERROR);
    }

    public function logout()
    {
        $user = $this->guard()->user();
        $this->guard()->logout();
        $user && CacheForget::CacheForget($user);
        LoginLog::createLoginLog('退出登录', $user['id']);
        return $this->succeed();
    }

    public function refresh()
    {
        return $this->respondWithToken($this->guard()->refresh());
    }

    private function respondWithToken(string $token, array $data = []): \Illuminate\Http\JsonResponse
    {
        return $this->succeed(array_merge([
            'token' => $token,
            'type' => 'Bearer',
            'expire' => config('jwt.ttl') * 60,
        ], $data));
    }
}
